package userShareModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func (UserShareModuleApi) GetShareList(c *gin.Context) {
	type share struct {
		model.ShareModel
		FileName  string `json:"fileName"`
		FileCover string `json:"fileCover"`
		FileType  uint8  `json:"fileType"`
		IsFolder  bool   `json:"isFolder"`
	}
	userId := utils.GetUserId(c)
	if userId == 0 {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	var shares []share // 使用用户定义的结构体
	err := global.DB.Table("share_models").
		Select(`
			share_models.*,
			file_models.file_name,
			file_models.file_cover,
			file_models.file_type,
			file_models.is_folder
		`).
		Joins("JOIN file_models ON file_models.id = share_models.file_id").
		Where("share_models.user_id = ? AND file_models.del_flag = ?", userId, enums.Normal).
		Scan(&shares).Error

	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.Errorf("GetShareList error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if len(shares) == 0 {
		res.OkWithData([]share{}, c)
		return
	}
	res.OkWithData(shares, c)
}
